import requests
import base64
import json

# 定义目标图片路径（需要分类的图片）
IMAGE_FILEPATH = "C:\\Users\\admin\\Desktop\\图像分类-未标注\\01.jpg"

# API请求参数，可指定返回前几个可能分类
PARAM = {"top_num": 2}

# 百度自定义图像分类模型API地址（已训练好的模型）
MODEL_API_URI = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/xxxxxxx"

# 百度智能云控制台中的密钥信息（用于获取access_token）
ACCESS_TOKEN = ""
API_KEY = "xxxxxxxxxxxxxxxxxxxxx"
SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxx"

# Step 1：自动获取access_token
if not ACCESS_TOKEN:
    print("1. ACCESS_TOKEN为空，调用鉴权接口获取TOKEN")
    auth_url = (
        "https://aip.baidubce.com/oauth/2.0/token?"
        f"grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRET_KEY}"
    )
    auth_resp = requests.get(auth_url)
    auth_resp_json = auth_resp.json()

    # 检查是否获取成功
    if "access_token" in auth_resp_json:
        ACCESS_TOKEN = auth_resp_json['access_token']
    else:
        print("❌ 获取access_token失败，请检查API Key和Secret Key")
        print(auth_resp_json)
        exit()

# Step 2：读取图片并进行Base64编码
print("2. 读取图片并编码")
try:
    with open(IMAGE_FILEPATH, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        base64_str = base64_data.decode("UTF8")
        print("✅ 图片已Base64编码")
except FileNotFoundError:
    print(f"❌ 找不到图片文件：{IMAGE_FILEPATH}")
    exit()

# 加入图片数据到请求参数
PARAM['image'] = base64_str

# Step 3：向模型接口发送请求
print("3. 向模型接口发送请求进行分类")
request_url = f"{MODEL_API_URI}?access_token={ACCESS_TOKEN}"
response = requests.post(url=request_url, json=PARAM)

# 处理返回结果
try:
    response_json = response.json()
    response_str = json.dumps(response_json, indent=4, ensure_ascii=False)
    print("✅ 分类结果如下：\n{}".format(response_str))
except Exception as e:
    print(f"❌ 接口返回异常: {e}")
    print(response.text)
